﻿package laan.xiaonei
{
    import com.adobe.crypto.*;
    import flash.events.*;
    import flash.net.*;
    import flash.utils.*;
    import laan.data.requestcenter.*;
	import remoting.json.JSON

    class APIRequester extends EventDispatcher
    {
        private var requestCenter:IRequestCenter;
        private var requestToHandlerMap:Dictionary;

        function APIRequester()
        {
            requestCenter = new RequestCenter(RequestType.QUEUE);
            requestToHandlerMap = new Dictionary();
            return;
        }// end function

        private function requestDataHandler(td:TokenData) : void
        {
            var handler:Function;
            var td:* = td;
            handler = requestToHandlerMap[td.request];
            delete requestToHandlerMap[td.request];
            if (handler != null)
            {
                try
                {
                    handler.call(null, JSON.decode(td.data));
                }
                catch (e:Error)
                {
                    handler.call(null, td.data);
                }
            }
            return;
        }// end function

        private function createSIG(obj:Object) : String
        {
            var _loc_3:String = null;
            var _loc_4:String = null;
            var _loc_2:Array = [];
            for (_loc_3 in obj)
            {
                
                _loc_2.push(_loc_3 + "=" + obj[_loc_3]);
            }
            _loc_2.sort();
            _loc_4 = _loc_2.join("");
            _loc_4 = _loc_4 + XiaoNeiConfig.SECRET_KEY;
            return MD5.hash(_loc_4);
        }// end function

        public function callAPI(obj:Object, handler:Function = null) : void
        {
            var _loc_5:String = null;
            obj.v = XiaoNeiConfig.VERSION;
            obj.api_key = XiaoNeiConfig.API_KEY;
            obj.call_id = new Date().time;
            obj.format = XiaoNeiConfig.DATA_FORMAT;
            obj.sig = createSIG(obj);
            var _loc_3:* = new URLRequest(XiaoNeiConfig.API_URL);
            _loc_3.method = URLRequestMethod.POST;
            var _loc_4:* = new URLVariables();
            for (_loc_5 in obj)
            {
                
                _loc_4[_loc_5] = obj[_loc_5];
            }
            _loc_3.data = _loc_4;
            trace(_loc_4);
            requestCenter.addRequest(_loc_3, requestDataHandler);
            requestToHandlerMap[_loc_3] = handler;
            return;
        }// end function

    }
}
